package com.weimei.conversionTreasure.http;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gtdev5.geetolsdk.mylibrary.beans.LoginInfoBean;
import com.weimei.conversionTreasure.utils.ValidateUtils;

import me.goldze.mvvmhabit.utils.SPUtils;
import me.goldze.mvvmhabit.utils.StringUtils;

/**
 * 本地数据源，可配合Room框架使用
 * Created by goldze on 2019/3/26.
 */
public class LocalDataSourceImpl implements LocalDataSource {
    private volatile static LocalDataSourceImpl INSTANCE = null;

    public static LocalDataSourceImpl getInstance() {
        if (INSTANCE == null) {
            synchronized (LocalDataSourceImpl.class) {
                if (INSTANCE == null) {
                    INSTANCE = new LocalDataSourceImpl();
                }
            }
        }
        return INSTANCE;
    }

    public static void destroyInstance() {
        INSTANCE = null;
    }

    private LocalDataSourceImpl() {
        //数据库Helper构建
    }

    @Override
    public void saveUserName(String userName) {
        SPUtils.getInstance().put("UserName", userName);
    }

    @Override
    public void savePassword(String password) {
        SPUtils.getInstance().put("password", password);
    }

    @Override
    public String getUserName() {
        return SPUtils.getInstance().getString("UserName");
    }

    @Override
    public String getPassword() {
        return SPUtils.getInstance().getString("password");
    }

    @Override
    public void setLogin(LoginInfoBean loginInfoBean) {
        SPUtils.getInstance().put("Login", new Gson().toJson(loginInfoBean));
    }

    @Override
    public LoginInfoBean getLoginInfo() {
        return new Gson().fromJson(SPUtils.getInstance().getString("Login"),
                new TypeToken<LoginInfoBean>() {
                }.getType());
    }

    @Override
    public boolean isLogin() {
        if (getLoginInfo() == null) {
            return false;
        } else {
            if (ValidateUtils.isNotEmptyObjectOrString(getLoginInfo())){
                if (ValidateUtils.isNotEmptyObjectOrString(getLoginInfo().getData())){
                    if (StringUtils.isEmpty(getLoginInfo().getData().getUser_id())) {
                        return false;
                    } else {
                        return true;
                    }
                }else {
                    return false;
                }
            }else {
                return false;
            }

        }

    }
}
